﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Text.RegularExpressions;
using System.Web.Caching;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.IO;

using Newtonsoft.Json;


namespace FractalistWX.Tool
{
    public class Tools
    {
        static LogWriter log = LogWriter.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/") + "log");

        public static bool CreateDirectory(string dir)
        {
            try
            {
                if (System.IO.Directory.Exists(dir))
                    return true;

                System.IO.Directory.CreateDirectory(dir);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static void DeleteDirectory(string dir)
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dir);
            di.Delete(true);
        }

        public static string GetFileName(string fileUrl)
        {
            Uri file = new Uri(fileUrl);
            int pos = file.AbsolutePath.LastIndexOf("/");
            if (pos >= 0 && pos < file.AbsolutePath.Length - 1)
            {
                return file.AbsolutePath.Substring(pos + 1);
            }
            else
            {
                return "";
            }
        }

        public static long GetFileSize(string filePath)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
            return fi.Length;
        }

        public static bool DownloadFile(string url, string localPath)
        {
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.DownloadFile(url, localPath);

                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 获得当前虚拟目录
        /// </summary>
        /// <returns></returns>
        public static String GetProductPath()
        {
            return (new System.Uri(HttpContext.Current.Request.Url, HttpContext.Current.Request.ApplicationPath.EndsWith("/") ? HttpContext.Current.Request.ApplicationPath : HttpContext.Current.Request.ApplicationPath + "/")).ToString();
        }

        /// <summary>
        /// 检查变量，如果不是文本，返回DefaultValue”
        /// </summary>
        /// <param name="str"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public static string CheckVar(object str, string DefaultValue)
        {
            try
            {
                if (str == null || str.ToString() == "" || (str.ToString().Trim().Length) == 0)
                {
                    return DefaultValue;
                }
                else
                {
                    return (str.ToString());
                }
            }
            catch
            {
                return DefaultValue;
            }
        }

        /// <summary>
        /// 检查变量，如果不是数值，返回DefaultValue
        /// </summary>
        /// <param name="str"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public static int CheckVar(object str, int DefaultValue)
        {
            try
            {
                if (str == null || str.ToString() == "" || str.ToString().Trim().Length == 0)
                {
                    return DefaultValue;
                }
                else
                {
                    return Convert.ToInt32(str);
                }

            }
            catch
            {
                return DefaultValue;
            }
        }

        public static Int64 CheckVar(object str, Int64 DefaultValue)
        {
            try
            {
                if (str == null || str.ToString() == "" || str.ToString().Trim().Length == 0)
                {
                    return DefaultValue;
                }
                else
                {
                    return Convert.ToInt64(str);
                }

            }
            catch
            {
                return DefaultValue;
            }
        }


        /// <summary>
        /// 检查变量，如果不是decimal，返回DefaultValue
        /// </summary>
        /// <param name="str"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public static decimal CheckVar(object str, decimal DefaultValue)
        {
            try
            {
                if (str == null || str.ToString() == "" || str.ToString().Trim().Length == 0)
                {
                    return DefaultValue;
                }
                else
                {
                    return Convert.ToDecimal(str);
                }

            }
            catch
            {
                return DefaultValue;
            }
        }


        /// <summary>
        /// 检查变量，如果不是布尔，返回DefaultValue
        /// </summary>
        /// <param name="str"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public static bool CheckVar(object str, bool DefaultValue)
        {
            try
            {
                if (Convert.ToBoolean(str))
                {
                    return Convert.ToBoolean(str);
                }
                else
                {
                    return DefaultValue;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 检查变量，如果不是long，返回DefaultValue
        /// </summary>
        /// <param name="str"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public static long CheckLVar(object str, long DefaultValue)
        {
            try
            {
                if (str == null || str.ToString() == "" || str.ToString().Trim().Length == 0)
                {
                    return DefaultValue;
                }
                else
                {
                    return Convert.ToInt64(str);
                }

            }
            catch
            {
                return DefaultValue;
            }
        }

        public static string AddZeroStr(string str, int no)
        {
            if (str.Length >= no)
            {
                return str;
            }
            else
            {
                int add = no - str.Length;
                string zeroStr = "";
                for (int i = 0; i < add; i++)
                {
                    zeroStr += "0";
                }
                return zeroStr + str;
            }
        }

        //屏蔽手机号
        public static string ShieldNumber(string userNumber)
        {
            string str = "";
            if (userNumber.Length == 11)
            {
                str = userNumber.Substring(0, 3) + "****" + userNumber.Substring(7);
            }
            return str;
        }

        public static string String2Json(string s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    case '\v':
                        sb.Append("\\v"); break;
                    case '\0':
                        sb.Append("\\0"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

        // 正则验证
        public static bool QuickValidate(string _express, string _value)
        {
            System.Text.RegularExpressions.Regex myRegex = new System.Text.RegularExpressions.Regex(_express);
            if (_value.Length == 0)
            {
                return false;
            }
            return myRegex.IsMatch(_value);
        }

        /// <summary>
        /// JavaScript弹出窗口，并跳转至指定Url
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="url"></param>
        public static void AlertMessage(System.Web.UI.Page page, string message, string url)
        {
            string js = @"<script language='JavaScript'>alert('" + message + "');window.location='" + url + "';</script>";
            if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "AlertMessage"))
            {
                page.ClientScript.RegisterStartupScript(page.GetType(), "AlertMessage", js, false);
            }
        }

        /// <summary>
        /// JavaScript弹出窗口
        /// </summary>
        /// <param name="msg"></param>
        public static void AlertMessage(System.Web.UI.Page page, string message)
        {
            string js = "<script language=\"JavaScript\">alert(\"" + message + "\");</script>";
            if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "AlertMessage"))
            {
                page.ClientScript.RegisterStartupScript(page.GetType(), "AlertMessage", js, false);
            }
        }

        /// <summary>
        /// JavaScript弹出窗口,并关闭当前页面
        /// </summary>
        /// <param name="msg"></param>
        public static void AlertMessageClose(System.Web.UI.Page page, string message)
        {
            string js = "<script language=\"JavaScript\">alert(\"" + message + "\");window.opener=null;window.close();</script>";
            if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "AlertMessage"))
            {
                page.ClientScript.RegisterStartupScript(page.GetType(), "AlertMessage", js, false);
            }
        }

        /// <summary>
        /// 执行JavaScript
        /// </summary>
        /// <param name="msg"></param>
        public static void ExeJS(System.Web.UI.Page page, string jsStr)
        {
            string js = "<script>" + jsStr + "</script>";
            if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "ExeJS"))
            {
                page.ClientScript.RegisterStartupScript(page.GetType(), "ExeJS", js, false);
            }
        }

        /// <summary>
        /// 执行JavaScript
        /// </summary>
        /// <param name="msg"></param>
        public static void JSRedirect(System.Web.UI.Page page, string url)
        {
            page.Response.Clear();
            page.Response.Write("<!DOCTYPE html><!--HTML5 doctype--><html><head><script>window.location='" + url + "';</script><title></title><body></body></html>");
            page.Response.End();
        }

        /// <summary>
        /// Ajax弹出提示框
        /// </summary>
        /// <param name="ButtonStr">页面按钮</param>
        /// <param name="MsgString">提示内容</param>
        public static void AjaxMyMsg(Button ButtonStr, string message, string url)
        {
            string js = @"alert('" + message + "');window.location='" + url + "';";
            ScriptManager.RegisterClientScriptBlock(ButtonStr, ButtonStr.GetType(), "ajs", js, true);
        }

        /// <summary>
        /// Ajax执行JS
        /// </summary>
        /// <param name="ButtonStr">页面按钮</param>
        /// <param name="jsstr">JS代码</param>
        public static void AjaxMyMsg(Button ButtonStr, string jsstr)
        {
            ScriptManager.RegisterClientScriptBlock(ButtonStr, ButtonStr.GetType(), "ajs", jsstr, true);
        }

        /// <summary>
        /// 获得随机数字
        /// </summary>
        /// <param name="BeginNum"></param>
        /// <param name="EndNum"></param>
        /// <returns></returns>
        public static int GetRandomNum(int BeginNum, int EndNum)
        {
            System.Random random = new Random();
            BeginNum = BeginNum - 1;
            EndNum = EndNum + 1;
            return (int)((int)((BeginNum - EndNum + 1) * random.NextDouble() + EndNum));
        }

        /// <summary>
        /// 获得时间（精确到毫秒）加4位随机数的文件名
        /// </summary>
        /// <returns>2006080411573211_2710</returns>
        public static string GetRandomFileNameStr()
        {
            string result = "";
            result = DateTime.Now.ToString("yyyyMMddHHmmssff");
            Random ra = new Random();
            result += "_" + ra.Next(1000, 9999).ToString();
            return result;
        }

        /// <summary>
        /// 判断一个字符串是不是完全由Number组成
        /// </summary>
        /// <param name="s">源字符串</param>
        /// <returns>True:源字符串是Number串；否则为False</returns>
        public static bool IsNumber(String s)
        {
            if (s.Length == 0)
            {
                return false;
            }

            foreach (Char c in s)
            {
                if (!Char.IsNumber(c))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 是否包含汉字
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsIncludeChinese(String s)
        {
            foreach (Char c in s)
            {
                UInt16 n = Convert.ToUInt16(c);
                if (n >= 0x4E00 && n < 0x9F00)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 判断一个字符串是不是完全由数字组成 
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>字符串是数字true，否则为false</returns>
        public static bool IsDigitString(String s)
        {
            if (s.Length == 0)
            {
                return false;
            }

            foreach (Char c in s)
            {
                if (!Char.IsDigit(c))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 判断一个字符串是不是完全由字母组成 
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>字符串是字母true，否则为false</returns>
        public static bool IsLetterString(String s)
        {
            if (s.Length == 0)
            {
                return false;
            }

            foreach (Char c in s)
            {
                if (!Char.IsLetter(c))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 判断一个字符串是不是完全由Ansi字母组成 
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>字符串是Ansi字母true，否则为false</returns>
        public static bool IsAnsiLetterString(String s)
        {
            if (s.Length == 0)
            {
                return false;
            }

            foreach (Char c in s)
            {
                if ((c.CompareTo('A') < 0) || (c.CompareTo('Z') > 0))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 判断一个字符串是不是Decimal
        /// </summary>
        /// <param name="s">源字符串</param>
        /// <returns>True:是；否则为False</returns>
        public static bool IsDecimal(String s)
        {
            if (s.Length == 0)
            {
                return false;
            }

            try
            {
                Convert.ToDecimal(s);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 取字符串左边开始的n个字符
        /// </summary>
        /// <param name="s">字符串</param>
        /// <param name="n">个数</param>
        /// <returns>左边开始的n个字符</returns>
        public static String Left(String s, int n)
        {
            if (n < s.Length)
            {
                return s.Substring(0, n) + "…";
            }
            else
            {
                return s;
            }
        }

        /// <summary>
        /// 取字符串右边的n个字符
        /// </summary>
        /// <param name="s">字符串</param>
        /// <param name="n">个数</param>
        /// <returns>右边开始的n个字符</returns>
        public static String Right(String s, int n)
        {
            if (n < s.Length)
            {
                return s.Substring(s.Length - n, n);
            }
            else
            {
                return s;
            }
        }

        /// <summary>
        /// 取字符串中间的字符
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static String Mid(String src, Int32 start, Int32 length)
        {
            if (start < 0)
            {
                throw new ArgumentException("param \"start\" illegal");
            }
            if (length < 1)
            {
                throw new ArgumentException("param \"length\" illegal");
            }

            String ret = String.Empty;
            Int32 srcLen = src.Length;

            if (src == null || src.Trim() == String.Empty)
            {
                return src;
            }

            if (start > srcLen)
            {
                throw new ArgumentException("param \"start\" illegal");
            }
            if ((start + length) > srcLen)
            {
                length = srcLen - start + 1;
            }
            start = start > 0 ? start - 1 : 0;
            ret = src.Substring(start, length);
            return ret;
        }

        /// <summary>
        /// 数组中查找目标串的位置。找到，返回从0开始计数的位置；未找到，返回负数。
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dest"></param>
        /// <returns></returns>
        public static Int32 SearchStringInArray(String[] src, String dest)
        {
            Int32 ret = -1;
            if (src == null || src.Length == 0 || dest == null)
            {
                return ret;
            }
            System.Array.Sort(src);
            ret = System.Array.BinarySearch(src, dest, new System.Collections.CaseInsensitiveComparer());
            return ret;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string GetTimeDesc(DateTime dateTime)
        {
            TimeSpan ts = DateTime.Now - dateTime;
            if (ts.TotalSeconds < 10)
            {
                return " 就在刚才";
            }

            if (ts.TotalSeconds < 60)
            {
                return (int)(ts.TotalSeconds) + " 秒钟前";
            }

            if (ts.TotalMinutes < 60)
            {
                return (int)(ts.TotalMinutes + 0.5) + " 分钟前";
            }

            if (ts.TotalHours < 24)
            {
                return (int)(ts.TotalHours + 0.5) + " 小时前";
            }

            if ((dateTime.Year == DateTime.Now.Year) && (dateTime.Month == DateTime.Now.Month))
            {
                return dateTime.ToString("当月dd日 HH:mm");
            }

            if (dateTime.Year == DateTime.Now.Year)
            {
                return dateTime.ToString("今年:MM-dd");
            }

            return dateTime.ToString("yyyy-MM-dd");
        }

        const String constHexChars = "0123456789ABCDEF";

        private static Byte HexCharToByte(Char h, Char l)
        {
            int hValue = constHexChars.IndexOf(Char.ToUpper(h));
            int lValue = constHexChars.IndexOf(Char.ToUpper(l));
            if (hValue == -1 || lValue == -1)
            {
                String error = String.Format("Invalid Hex Number Char : {0}", h);
                throw new Exception(error);
            }

            return Convert.ToByte(hValue * 16 + lValue);
        }

        /// <summary>
        /// 转换一个整型数组到字符串
        /// </summary>
        /// <param name="AnIntAry">需要转换的数组</param>
        /// <param name="ASep">分隔符</param>
        /// <returns></returns>
        public static string IntAryToString(int[] AnIntAry, string ASep)
        {
            bool first = true;
            string ret = "";
            for (int i = 0; i < AnIntAry.Length; i++)
            {
                if (!first)
                {
                    ret += ASep;
                }
                else
                {
                    first = false;
                }
                ret += AnIntAry[i].ToString();
            }
            return ret;
        }

        /// <summary>
        /// 过滤指定的字符
        /// </summary>
        /// <param name="raw">源字符</param>
        /// <param name="toFilterStr">要过滤掉的字符</param>
        /// <returns></returns>
        public static String Filter(String raw, String toFilterStr)
        {
            if (toFilterStr == null || toFilterStr == String.Empty)
            {
                return raw;
            }
            Char[] delimiter = toFilterStr.ToCharArray();
            String[] retArray = raw.Split(delimiter);
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (String obj in retArray)
            {
                if (obj != String.Empty)
                {
                    sb.Append(obj);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 过滤Sql注入字符串
        /// </summary>
        /// <param name="strChar"></param>
        /// <returns></returns>
        public static string SafeSql(string sSql)
        {
            string retVal = "";
            if (sSql != null && sSql != "")
            {
                retVal = sSql.Replace("'", "''");
            }
            else
            {
                retVal = "";
            }           
            return retVal;
        }
        public static string SafeSql(string inputString, int maxLength) 
        {  
            // 检查是否为空 
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();                

                //检查长度 
                if (maxLength > 0)
                {
                    if (inputString.Length > maxLength)
                        inputString = inputString.Substring(0, maxLength);
                }
                //替换危险字符 
                inputString = inputString.Replace("\"", "&quot;");
                inputString = inputString.Replace("'", "'"); 
                inputString = inputString.Replace("<", "&lt;");
                inputString = inputString.Replace(">", "&gt;"); 
                inputString = inputString.Replace("&", "&amp;");                
                inputString = string.IsNullOrEmpty(inputString) ? "" : inputString.Replace("'", "''");
                inputString = new Regex("exec", RegexOptions.IgnoreCase).Replace(inputString, "&#101;xec");
                inputString = new Regex("xp_cmdshell", RegexOptions.IgnoreCase).Replace(inputString, "&#120;p_cmdshell");
                inputString = new Regex("select", RegexOptions.IgnoreCase).Replace(inputString, "&#115;elect");
                inputString = new Regex("insert", RegexOptions.IgnoreCase).Replace(inputString, "&#105;nsert");
                inputString = new Regex("update", RegexOptions.IgnoreCase).Replace(inputString, "&#117;pdate");
                inputString = new Regex("delete", RegexOptions.IgnoreCase).Replace(inputString, "&#100;elete");
                inputString = new Regex("drop", RegexOptions.IgnoreCase).Replace(inputString, "&#100;rop");
                inputString = new Regex("create", RegexOptions.IgnoreCase).Replace(inputString, "&#99;reate");
                inputString = new Regex("rename", RegexOptions.IgnoreCase).Replace(inputString, "&#114;ename");
                inputString = new Regex("truncate", RegexOptions.IgnoreCase).Replace(inputString, "&#116;runcate");
                inputString = new Regex("alter", RegexOptions.IgnoreCase).Replace(inputString, "&#97;lter");
                inputString = new Regex("exists", RegexOptions.IgnoreCase).Replace(inputString, "&#101;xists");
                inputString = new Regex("master.", RegexOptions.IgnoreCase).Replace(inputString, "&#109;aster.");
                inputString = new Regex("restore", RegexOptions.IgnoreCase).Replace(inputString, "&#114;estore");
            }
            return inputString;
        }
        /// <summary>
        /// 获取Get请求的所有参数
        /// </summary>
        /// <returns>请求参数字符串</returns>
        public static SortedDictionary<string, string> GetRequestGet()
        {
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            //对url第一个字符？过滤
            string query = HttpContext.Current.Request.Url.Query.Replace("?", "");
            if (!string.IsNullOrEmpty(query))
            {
                //根据&符号分隔成数组
                string[] coll = query.Split('&');
                //定义临时数组
                string[] temp = { };
                //循环各数组
                for (int i = 0; i < coll.Length; i++)
                {
                    //根据=号拆分
                    temp = coll[i].Split('=');
                    //把参数名和值分别添加至SortedDictionary数组
                    sArray.Add(temp[0], temp[1]);
                }
            }
            return sArray;
        }

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="Password"></param>
        /// <returns></returns>
        public static string Encrypt(string Password)
        {
            string str = "";
            FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(Password, false, 60);
            str = FormsAuthentication.Encrypt(ticket).ToString();
            return str;
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="Passowrd"></param>
        /// <returns></returns>
        public static string Decrypt(string Passowrd)
        {
            string str = "";
            str = FormsAuthentication.Decrypt(Passowrd).Name.ToString();
            return str;
        }

        /// <summary>
        /// MD5加密算法
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string MD5(string content)
        {
            byte[] b = System.Text.Encoding.UTF8.GetBytes(content);
            b = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');
            return ret;
        }

        public static string DesEncrypt(string Text)
        {
            return DesEncrypt(Text, "desKey");
        }

        public static string DesEncrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        public static string DesDecrypt(string Text)
        {
            return DesDecrypt(Text, "desKey");
        }

        public static string DesDecrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        public static string ToBase64(string content)
        {
            byte[] cbt = System.Text.Encoding.UTF8.GetBytes(content);
            try
            {
                return Convert.ToBase64String(cbt);
            }
            catch
            {
                return content;
            }
        }

        public static string GetBase64(string content)
        {
            byte[] bt = Convert.FromBase64String(content);
            try
            {
                while (content.Length % 4 != 0)
                {
                    content += "=";
                }
                return System.Text.UTF8Encoding.UTF8.GetString(bt);
            }
            catch
            {
                return content;
            }
        }

        /// <summary>
        /// 将对象放入缓存
        /// </summary>
        /// <param name="cachekey"></param>
        /// <param name="obj"></param>
        public static void AddCache(string cachekey, object obj)
        {
            if (obj != null)
            {
                Cache c = HttpRuntime.Cache;
                c.Insert(cachekey, obj, null, DateTime.Now.AddHours(1.5), Cache.NoSlidingExpiration);
            }
        }

        /// <summary>
        /// 清缓存
        /// </summary>
        /// <param name="cachekey"></param>
        /// <param name="obj"></param>
        public static void ClearCache(string cachekey)
        {
            Cache c = HttpRuntime.Cache;
            c.Remove(cachekey);
        }

        /// <summary>
        /// 返回缓存数据 
        /// </summary>
        /// <param name="cachekey"></param>
        /// <returns></returns>
        public static object GetCache(string cachekey)
        {
            Cache c = HttpRuntime.Cache;
            if (c[cachekey] != null)
                return c[cachekey];
            return null;
        }

        public static void RemoveAllCache(string cachekey)
        {
            System.Web.Caching.Cache c = HttpRuntime.Cache;
            c.Remove(cachekey);

        }

        public static string HTMLEnCode(string sHTML)
        {
            string sTemp = "";
            if (sHTML.Length == 0)
            {
                return "";
            }
            sTemp = sHTML.Replace("&nbsp;", " ");
            sTemp = sTemp.Replace("&", "&amp;");
            sTemp = sTemp.Replace("<", "&lt;");
            sTemp = sTemp.Replace(">", "&gt;");
            sTemp = sTemp.Replace("'", "&#39;");
            sTemp = sTemp.Replace(" ", "&nbsp;");
            sTemp = sTemp.Replace("\"", "&quot;");
            return sTemp;
        }

        public static string HTMLTrans(string sHTML)
        {
            return sHTML.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace(" ", "&nbsp;");
        }

        /// <summary>
        /// 秒数转日期
        /// </summary>
        /// <param name="Value">秒数</param>
        /// <returns>日期</returns>
        public static DateTime GetGMTDateTime(int Value)
        {
            //GMT时间从1970年1月1日开始，先把它作为赋为初值
            long Year = 1970, Month = 1, Day = 1;
            long Hour = 0, Min = 0, Sec = 0;
            //临时变量
            long iYear = 0, iDay = 0;
            long iHour = 0, iMin = 0, iSec = 0;
            //计算文件创建的年份
            iYear = Value / (365 * 24 * 60 * 60);
            Year = Year + iYear;
            //计算文件除创建整年份以外还有多少天
            iDay = (Value % (365 * 24 * 60 * 60)) / (24 * 60 * 60);
            //把闰年的年份数计算出来
            int RInt = 0;
            for (int i = 1970; i < Year; i++)
            {
                if ((i % 4) == 0)
                    RInt = RInt + 1;
            }
            //计算文件创建的时间(几时)
            iHour = ((Value % (365 * 24 * 60 * 60)) % (24 * 60 * 60)) / (60 * 60);
            Hour = Hour + iHour;
            //计算文件创建的时间(几分)
            iMin = (((Value % (365 * 24 * 60 * 60)) % (24 * 60 * 60)) % (60 * 60)) / 60;
            Min = Min + iMin;
            //计算文件创建的时间(几秒)
            iSec = (((Value % (365 * 24 * 60 * 60)) % (24 * 60 * 60)) % (60 * 60)) % 60;
            Sec = Sec + iSec;
            DateTime t = new DateTime((int)Year, (int)Month, (int)Day, (int)Hour, (int)Min, (int)Sec);
            DateTime t1 = t.AddDays(iDay - RInt);
            return t1;
        }



        /// <summary>
        /// 当前日期时间，转换为秒
        /// </summary>
        /// <returns>秒数</returns>
        public static string xDateSeconds(DateTime d)
        {
            long xdateseconds = 0;
            DateTime xdatenow = d;     //当前UTC时间


            long xminute = 60;      //一分种60秒
            long xhour = 3600;
            long xday = 86400;
            long byear = 1970;//从1970-1-1 0：00：00开始到现在所过的秒
            long[] xmonth = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
            long[] xyear = { 365, 366 };
            long num = 0;

            xdateseconds += xdatenow.Second;    //算秒
            xdateseconds += xdatenow.Minute * xminute;      //算分
            xdateseconds += xdatenow.Hour * xhour;      //算时
            xdateseconds += (xdatenow.Day - 1) * xday;        //算天

            //算月(月换成天算)
            if (DateTime.IsLeapYear(xdatenow.Year))
            {
                xdateseconds += (xmonth[xdatenow.Month - 1] + 1) * xday;
            }
            else
            {
                xdateseconds += (xmonth[xdatenow.Month - 1]) * xday;
            }

            //算年（年换成天算）
            long lyear = xdatenow.Year - byear;

            for (int i = 0; i < lyear; i++)
            {
                if (DateTime.IsLeapYear((int)byear + i))
                {
                    num++;
                }
            }

            xdateseconds += ((lyear - num) * xyear[0] + num * xyear[1]) * xday;

            return xdateseconds.ToString();
        }

        public static string SendSMS(string mobile, string content)
        {
            string re = "";
            System.Net.WebClient oWebClient = new System.Net.WebClient();

            string postData = "account=sdk_shengan&password=60326851&destmobile=" + mobile + "&msgText=" + content;
            byte[] uploadData = System.Text.Encoding.UTF8.GetBytes(postData);
            oWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            oWebClient.Headers.Add("ContentLength", uploadData.Length.ToString());

            try
            {
                re = System.Text.Encoding.GetEncoding("UTF-8").GetString(oWebClient.UploadData("http://www.jianzhou.sh.cn/JianzhouSMSWSServer/http/sendBatchMessage", "POST", uploadData));
            }
            catch
            {
                log.WriteLog("短信下发异常:" + mobile + "|" + content);
            }
            return re;
        }

       

        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        public static string ImageToBase64(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }

        //public static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors)
        //{
        //    return true;
        //}
    }
}
